import React, { Suspense, lazy, useMemo } from 'react'
import { BrowserRouter, useRoutes, Routes, Route, Navigate, useLocation, useNavigate } from 'react-router-dom'
import { RouteType } from '../types'
import { asyncRoutes } from './routes'
import { useDispatch, useSelector } from 'react-redux'
import { getUserInfo } from '../api'
const Signin = lazy(() => import('../views/signin'))
const MainLayout = lazy(() => import('../mainLayout'))

// 路由前置守卫
const BeforeRouterEach: React.FC<{
	Comp: JSX.Element
}> = ({ Comp }) => {
	const dispatch = useDispatch()
	const navigate = useNavigate()
	const permission_ids = useSelector((state: any) => state.userInfo.permission_ids)
	// 白名单 免登录
	const whiteList = ['/signin']
	const location = useLocation()
	// 拦截
	const token = localStorage.getItem('token');
	// token 存在
	if (token) {
		if (permission_ids) {
			return Comp
		} else {
			// token存在 权限不存在
			getUserInfo(token).then(resp => {
				const { code, message, data } = resp;
				if (code === 0) {
					dispatch({ type: 'loginSuccess', payload: { ...data, token } })
				} else {
					dispatch({ type: 'loginFail' });
					localStorage.removeItem('token')
					navigate("/signin")
				}
			})
			return <div></div>
		}
	} else {
		// token 不存在
		if (!whiteList.includes(location.pathname)) {
			// 重定向进入登录
			return <Navigate to="/signin"></Navigate>
		} else {
			return Comp
		}
	}

}

const generatorRoute = (routes: RouteType[], permission_ids: string): any => {
	return routes.map((v, i) => {
		"110, 120, 130"

		// 获取当前是否路由权限
		const isPermission = v.meta ? v.meta.permission_id ? permission_ids.includes(v.meta.permission_id) : false : false
		return v.element
			? isPermission && <Route key={i} path={v.path} element={<BeforeRouterEach Comp={v.element}></BeforeRouterEach>}></Route>
			: v.children && generatorRoute(v.children, permission_ids)
	})
}

const Router = () => {
	const permission_ids = useSelector((state: any) => state.userInfo.permission_ids);
	// 惰性请求
	// 路由

	const routeView = useMemo(() => {
		console.log('路由');
		// 返回当前权限所具有的路由
		return generatorRoute(asyncRoutes, permission_ids)
	}, [permission_ids])

	return (
		<BrowserRouter>
			<Suspense fallback={<div>页面加载中...</div>}>
				<Routes>
					<Route path="/" element={<BeforeRouterEach Comp={<MainLayout></MainLayout>}></BeforeRouterEach>}>
						{routeView}
					</Route >

					<Route path="/signin" element={<BeforeRouterEach Comp={<Signin></Signin>}></BeforeRouterEach>}></Route>

					<Route path="*" element={ <BeforeRouterEach Comp={<div>404页面</div>}></BeforeRouterEach>}></Route>
				</Routes >
			</Suspense >
		</BrowserRouter >
	)
}

export default Router